package com.atguigu.lease.web.admin.service.impl;


import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.web.admin.service.FileService;

import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.SneakyThrows;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private MinioProperties minioProperties;
    @Autowired
    private MinioClient minioClient;

    @SneakyThrows
    @Override
    public String upload(MultipartFile file) {
        //获得文件拓展名
        String extension = StringUtils.getFilenameExtension(file.getOriginalFilename());
        //获取随机文件名
        String filename = UUID.randomUUID().toString().replace("-", "");
        //获得日期文件夹
        String date = new DateTime().toString("yyyy/MM/dd");

        InputStream inputStream = file.getInputStream();
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .bucket(minioProperties.getBucket())
                .object(date + "/" + filename + "." + extension)
                .stream(inputStream, file.getSize(), -1)
                .build();
        minioClient.putObject(putObjectArgs);

        return minioProperties.getEndpoint() + "/" + minioProperties.getBucket() + "/" + date + "/" + filename + "." + extension;
    }
}
